package com.lky.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 名称:MyInterceptor
 * 描述:
 *
 * @version 1.0
 * @author:likaiyang
 * @datetime:2023-11-02 17:03
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception{
        String uri=request.getRequestURI();//获取请求路径
        if(uri.indexOf("/login")>=0||uri.indexOf("/tologin")>=0 ||
                uri.indexOf("/toregister")>=0||uri.indexOf("/register")>=0||
                uri.indexOf("/css")>=0){//登录操作、前往登录页面、注册操作、前往注册页面都不能被拦截
            return true;//对用户登录的相关请求放行
        }
        HttpSession session=request.getSession();
        if(session.getAttribute("USER_SESSION")!=null){
            return true;//用户已登录，放行
        }
        //其他情况都直接跳转至登录页面
        request.setAttribute("msg","您还没有登录，请先进行登录！");
        request.getRequestDispatcher("../login.jsp").forward(request,response);
        return false;
    }
}
